<template>
	<view class="shoppingCar">
		<view class="empty" v-if="dataList.length == 0">
			<view style="text-align: center;">
				<image src="../../static/images/denglu.png" mode="scaleToFill"></image>
				<view class="desction" v-if="isLogin">
					您得购物车是空得哦，快去逛逛把~
				</view>
				<view class="loginBtn" v-if="!isLogin" @tap="goLogin">
					登录/注册
				</view>
			</view>
		</view>
		<view class="topbg" v-if="dataList.length > 0">
		</view>
		<view class="content" v-if="dataList.length > 0">
			<view class="uni-list shopLsit">
				<checkbox-group>
					<view class="uni-list-cell shop" v-for="(item,index) in dataList" :key="index">
						<view class="header">
							<!-- #ifdef MP-ALIPAY -->
								<checkbox @change="checkShop(item)" color="#ff4500" :checked="item.checked" :value="item.cartId"  />
							<!-- #endif -->
							
							<!-- #ifndef MP-ALIPAY -->
								<checkbox @tap="checkShop(item)" color="#ff4500" :checked="item.checked" :value="item.cartId"  />
							<!-- #endif -->
							
							
							<image class="shopImg" src="../../static/images/store.png" mode="scaleToFill"></image>
							<text @tap="goStore(item.storeId)">{{item.storeName}}</text>
							<image @tap="goStore(item.storeId)" class="goStore" src="../../static/images/quanbu.png" mode="scaleToFill"></image>
						</view>
						<view class="uni-list commodityList">
							<checkbox-group>

								<view class="uni-list-cell commodityBox" v-for=" (commodity,indexs) in item.itemList" :key="indexs">
									<view class="box" @touchstart="touchStart($event,indexs,index)" @touchend="touchEnd($event,indexs,index)"
									 @touchmove="touchMove($event,indexs,index)" :style="{transform:'translate3d('+commodity.slide_x+'px, 0, 0)'}">
										<view style="padding-right: 30upx;box-sizing: border-box;width: 670upx;">
											<view class="commodityInfo">
												<!-- #ifdef MP-ALIPAY -->
												<checkbox color="#ff4500" border-radius="50%" :checked="commodity.checked" :value="commodity.id" @change="checkCommodity(commodity)" />
												<!-- #endif -->
												
												<!-- #ifndef MP-ALIPAY -->
													<checkbox color="#ff4500"  :checked="commodity.checked" :value="commodity.id" @tap="checkCommodity(commodity)" />
												<!-- #endif -->
												
												<view class="commodity" @tap="goCommodityInfo(commodity)">
													<image :src="commodity.productPic" lazy-load="true" mode="scaleToFill"></image>
													<view class="info">
														<view class="title">
															{{commodity.productName}}
														</view>
														<view class="norms">
															<text v-if="commodity.sp1">{{commodity.sp1}}</text>
															<text v-if="commodity.sp2">/{{commodity.sp2}}</text>
															<text v-if="commodity.sp3">/{{commodity.sp3}}</text>
														</view>
													</view>
													<view class="xiajiaImg" v-if="commodity.productPublishType == 1">
														<image src="../../static/images/xiajia.png" mode="scaleToFill"></image>
													</view>
												</view>
											</view>
											<view class="priceBox">
												<view class="price">
													￥<text>{{commodity.price}}</text>
												</view>
												<view class="num">
													<view @tap="less(commodity)" class="less" :class="{disabled: commodity.productQuantity == 1}">
														-
													</view>
													<input type="number" @input="inputChange(commodity)" v-model="commodity.productQuantity" />
													<view @tap="add(commodity)" class="add">
														+
													</view>
												</view>
											</view>
										</view>

										<view class="group-btn">
											<view class="removeM btn-div" @tap="removeM(index, commodity)">
												删除
											</view>
										</view>
									</view>
								</view>
							</checkbox-group>
						</view>
					</view>
				</checkbox-group>
			</view>
		</view>
		<view class="bottomPay" v-if="dataList.length>0">
			<checkbox-group @change="checkAll('all')">
				<checkbox color="#ff4500" :checked="checkedAll" value="1" /><text>全选</text>
			</checkbox-group>
			<view class="payBox">
				<view class="payNum">
					合计：<text>￥{{payNum.toFixed(2)}}</text>
				</view>
				<view class="payBtn" @tap="payMoney">
					去结算
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				dataList: [],
				payNum: 0,
				checkedAll: false,
				commodityId: "",
				delBtnWidth: 0, //删除按钮宽度单位（rpx）
				start_slide_x: 0,
				btnWidth: 0,
				startX: 0,
				LastX: 0,
				startH: 0,
				endH: 0,
				startTime: 0,
				isLogin: false
			}
		},
		onLoad() {

		},
		onShow() {
			this.getData();
			this.checkedAll = false;
			this.payNum = 0;
			if (uni.getStorageSync('buyerAccountId')) {
				this.isLogin = true
			} else {
				this.isLogin = false
			}
		},
		methods: {
			getData() {
				let data = {}
				this.$http.post(this.$http.baseUrl + '/api/v1.0/cart/getCartList', data, res => {
					let dataList = res.data.data.cartList
					for (let i = 0; i < dataList.length; i++) {
						dataList[i].checked = false;
						for (let j = 0; j < dataList[i].itemList.length; j++) {
							dataList[i].itemList[j].checked = false;
							dataList[i].itemList[j].slide_x = 0;
						}
					}
					this.dataList = dataList;
				})
			},
			goStore(id) {
				uni.navigateTo({
					url: '../shop/shop?shopId=' + id
				})
			},
			payMoney() {
				let selectList = []
				let count = 0; //商品总数
				let freight = []; //邮费
				for (let i = 0; i < this.dataList.length; i++) {
					let itemList = [];
					let shopCount = 0;
					let money = 0; //单个商店总价
					for (let j = 0; j < this.dataList[i].itemList.length; j++) {
						if (this.dataList[i].itemList[j].checked == true && this.dataList[i].itemList[j].productPublishType == 1) {
							uni.showToast({
								title: "订单中存在已下架商品，请重新选择",
								icon: 'none'
							})
							return
						} else {

							if (this.dataList[i].itemList[j].checked == true) {
								this.dataList[i].itemList[j].count = this.dataList[i].itemList[j].productQuantity
								itemList.push(this.dataList[i].itemList[j])
								count += this.dataList[i].itemList[j].productQuantity;
								shopCount += this.dataList[i].itemList[j].productQuantity;
								money += this.dataList[i].itemList[j].price * this.dataList[i].itemList[j].productQuantity;
								freight.push(this.dataList[i].itemList[j].shopFee)

							}
						}
					}
					if (itemList.length > 0) {
						selectList.push({
							"accountId": uni.getStorageSync('buyerAccountId'),
							"freightAmount": freight.sort()[freight.length - 1],
							"merchantId": this.dataList[i].merchantId,
							"storeId": this.dataList[i].storeId,
							"storeName": this.dataList[i].storeName,
							productList: itemList,
							money: money,
							shopCount: shopCount
						})
					}

				}
				
				if (selectList.length == 0) {
					return false;
				}
				let data = {
					"addressId": "",
					"count": count,
					"storeList": selectList,
				}
				uni.navigateTo({
					url: '../myorder/carCreatOrder?data=' + encodeURIComponent(JSON.stringify(data))
				})
			},
			checkCommodity(item) {
				item.checked = !item.checked;
				console.log(item.checked)
				for (let j = 0; j < this.dataList.length; j++) {
					for (let z = 0; z < this.dataList[j].itemList.length; z++) {
						if (this.dataList[j].itemList[z].id == item.id) {
							for (let i = 0; i < this.dataList[j].itemList.length; i++) {
								if (this.dataList[j].itemList[i].checked == false) {
									this.dataList[j].checked = false;
									break;
								} else {
									this.dataList[j].checked = true;
								}
							}
						}
					}
				}
				for (let i = 0; i < this.dataList.length; i++) {
					if (this.dataList[i].checked == false) {
						this.checkedAll = false;
						break;
					} else {
						this.checkedAll = true;
					}
				}
				this.calcNum()

			},
			checkAll(e) {
				if (e == 'all') {
					//全选情况
					if (this.checkedAll == false) {
						for (let i = 0; i < this.dataList.length; i++) {
							this.dataList[i].checked = true;
							for (let j = 0; j < this.dataList[i].itemList.length; j++) {
								this.dataList[i].itemList[j].checked = true;
								this.calcNum()
							}
						}
						this.checkedAll = true;
					} else {
						for (let i = 0; i < this.dataList.length; i++) {
							this.dataList[i].checked = false;
							for (let j = 0; j < this.dataList[i].itemList.length; j++) {
								this.dataList[i].itemList[j].checked = false;
							}
						}
						this.payNum = 0;
						this.checkedAll = false;
					}
				}

			},
			checkShop(item) {
				item.checked = !item.checked
				for (let i = 0; i < item.itemList.length; i++) {
					item.itemList[i].checked = item.checked
				}

				for (let i = 0; i < this.dataList.length; i++) {
					if (this.dataList[i].checked == false) {
						this.checkedAll = false;
						break;
					} else {
						this.checkedAll = true;
					}
				}
				this.calcNum()


			},
			calcNum() {
				let num = 0;
				for (let i = 0; i < this.dataList.length; i++) {
					for (let j = 0; j < this.dataList[i].itemList.length; j++) {
						if (this.dataList[i].itemList[j].checked == true) {
							num += this.dataList[i].itemList[j].price * this.dataList[i].itemList[j].productQuantity
						}
					}
				}
				this.payNum = num;
			},
			goCommodityInfo(item) {

				uni.navigateTo({
					url: "/pages/details/details?id=" + item.productId
				})
			},
			less(item) {
				if (item.productQuantity > 1) {
					let data = {
						id:item.id,
						quantity:item.productQuantity-1
					}
					this.$http.post('/api/v1.0/cart/updateQuantity',data,res=>{
						console.log(res.data);
						if(res.data.status == '000000'){
							item.productQuantity--
							this.calcNum()
						}else{
							uni.showToast({
								title:res.data.message,
								icon:'none'
							})
						}
					})
				} else {
					item.productQuantity = 1
				}
			},
			add(item) {
				let data = {
					id:item.id,
					quantity:item.productQuantity+1
				}
				this.$http.post('/api/v1.0/cart/updateQuantity',data,res=>{
					console.log(res.data);
					if(res.data.status == '000000'){
						item.productQuantity++
						this.calcNum()
					}else{
						uni.showToast({
							title:res.data.message,
							icon:'none'
						})
					}
				})
			},
			inputChange(item){
				let data = {
					id:item.id,
					quantity:item.productQuantity
				}
				this.$http.post('/api/v1.0/cart/updateQuantity',data,res=>{
					console.log(res.data);
					if(res.data.status == '000000'){
						
						this.calcNum()
					}else{
						uni.showToast({
							title:res.data.message,
							icon:'none'
						})
					}
				})
			},
			// 滑动开始
			touchStart(e, index, i) {
				// console.log(e)
				//记录手指放上去的时间
				this.startTime = e.timeStamp;
				//记录滑块的初始位置
				this.start_slide_x = this.dataList[i].itemList[index].slide_x;
				// 按钮宽度
				uni.createSelectorQuery()
					.selectAll('.group-btn')
					.boundingClientRect()
					.exec(res => {
						if (res[0] != null) {
							this.btnWidth = res[0][index].width * -1;
						}
					});
				// 记录上一次开始时手指所处位置
				this.startX = e.changedTouches[0].pageX;
				this.startH = e.changedTouches[0].clientY;
				// console.log(this.startH)
				// 记录上一次手指位置
				this.lastX = this.startX;
				//初始化非当前滑动消息列的位置
				this.dataList[i].itemList.forEach((item, eq) => {
					if (eq !== index) {
						item.slide_x = 0;
					}
				});
				this.dataList.forEach((item, eq) => {
					if (eq !== i) {
						this.dataList[eq].itemList.forEach((item2, eq2) => {
							item2.slide_x = 0;
						})
					}
				});
			},
			// 滑动中
			touchMove(e, index, i) {
				const endX = e.changedTouches[0].pageX;
				const distance = endX - this.lastX;
				// 预测滑块所处位置
				const duang = this.dataList[i].itemList[index].slide_x + distance;
				// 如果在可行区域内
				if (duang <= 0 && duang >= this.btnWidth) {
					this.dataList[i].itemList[index].slide_x = duang;
				}
				this.lastX = endX;
			},
			// 滑动结束
			touchEnd(e, index, i) {
				this.endH = e.changedTouches[0].clientY
				// console.log(this.startH, this.endH)
				// console.log(Math.abs(this.endH - this.startH))
				// 判断手指最终位置与手指开始位置的位置差距
				if (Math.abs(this.endH - this.startH) < 20) {
					let distance = 10;
					const endTime = e.timeStamp;
					const x_end_distance = this.startX - this.lastX;
					if (Math.abs(endTime - this.startTime) > 200) {
						distance = this.btnWidth / -2;
					}

					if (x_end_distance > distance) {
						this.dataList[i].itemList[index].slide_x = this.btnWidth;
					} else if (x_end_distance < distance * -1) {
						this.dataList[i].itemList[index].slide_x = 0;
					} else {
						this.dataList[i].itemList[index].slide_x = this.start_slide_x;
					}
				} else {
					// this.dataList[i].itemList[index].slide_x = 0;
				}

			},
			removeM(i, item) {
				var _this = this;
				uni.showModal({
					content: '确定要把该商品从购物车删除吗？',
					confirmColor: "#F63810",
					success: function(res) {
						if (res.confirm) {
							let data = {
								"delForms": [{
									"cartId": item.cartId,
									"ids": [item.id]
								}],
							}
							_this.$http.post('/api/v1.0/cart/deleteCartItem', data, res => {
								if (res.data.status == '000000') {
									uni.showToast({
										title: "删除成功！",
										icon: "none"
									})
								} else {
									uni.showToast({
										title: "删除失败，请稍后再试！",
										icon: "none"
									})
								}

								_this.getData()
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});


			},
			goLogin() {
				uni.navigateTo({
					url: '../login/login'
				})
			}
		},
		watch: {
			dataList(newval, oldval) {
				// console.log(newval,oldval)
			},
			deep: true

		}
	}
</script>

<style lang="scss">
	.shoppingCar {
		background-color: #f4f4f4;
		min-height: 100vh;

		.empty {
			height: 100vh;
			display: flex;
			align-items: center;
			justify-content: center;
			text-align: center;

			image {
				width: 343upx;
				height: 232upx;
				margin-bottom: 60upx;
			}

			.desction {
				font-size: 30upx;
				color: #999;
			}

			.loginBtn {
				width: 197upx;
				height: 66upx;
				border: 1upx solid #F63810;
				display: flex;
				align-items: center;
				justify-content: center;
				color: #F63810;
				font-size: 30upx;
				margin: 0 auto;
				border-radius: 10upx;
			}
		}

		.topbg {
			background: linear-gradient(to bottom, #FC3F0C 0%, #E8271B 100%);
			width: 100%;
			height: 309upx;
		}

		.content {
			position: relative;
			top: -180upx;
			width: 100%;
			z-index: 99;


			.shopLsit {
				width: 694upx;
				margin: 0 auto;

				// background-color: #fff;
				.shop {
					background-color: #fff;
					border-radius: 20upx;
					margin-bottom: 20upx;

					checkbox {
						width: 44upx;
						height: 44upx;
						margin-right: 30upx;
						border-radius: 50%;
						
					}
					//#ifdef MP-ALIPAY
					.checkbox-text {
					  font-size:34rpx;
					  line-height: 1.2;
					  color: green !important;
					}
					
					//#endif


					.header {
						border-bottom: 1upx solid #f2f2f2;
						height: 84upx;
						display: flex;
						align-items: center;
						padding-left: 30upx;
						box-sizing: border-box;

						.shopImg {
							width: 36upx;
							height: 36upx;
							margin: 0 11upx 0 30upx;
						}

						text {
							font-size: 28upx;
							color: #333;
							font-weight: bold;
						}

						.goStore {
							width: 22upx;
							height: 22upx;
						}
					}

					.commodityList {
						width: 100%;
						overflow: hidden;

						.commodityBox {
							padding: 30upx 30upx 40upx;
							display: flex;
							justify-content: flex-start;
							flex-wrap: nowrap;
							position: relative;

							.box {
								padding-right: 30upx;
								box-sizing: border-box;
								width: 670upx;
								display: flex;
								flex-wrap: nowrap;
							}

							.commodityInfo {
								display: flex;
								justify-content: space-between;
								align-items: center;

								.commodity {
									width: 590upx;
									display: flex;
									justify-content: flex-start;

									image {
										width: 150upx;
										height: 150upx;
										margin-right: 25upx;
									}

									.info {
										width: 341upx;

										.title {
											font-size: 28upx;
											color: #333;
											display: -webkit-box;
											overflow: hidden;
											white-space: normal !important;
											text-overflow: ellipsis;
											word-wrap: break-word;
											-webkit-line-clamp: 2;
											-webkit-box-orient: vertical;
										}

										.norms {
											color: #4d4d4d;
											font-size: 24upx;
											padding: 10upx 20upx;
											background-color: #f2f2f2;
											display: inline-block;
											margin-top: 20upx;
											border-radius: 10upx;
										}
									}
								}

								.xiajiaImg {
									width: 123upx;
									height: 123upx;
									opacity: 0.8;
									position: absolute;
									bottom: 60upx;
									right: 50upx;

									image {
										width: 100%;
										height: 100%;
									}
								}
							}

							.priceBox {
								display: flex;
								justify-content: flex-end;
								margin-top: 30upx;

								.price {
									font-size: 24upx;
									font-weight: bold;
									margin-right: 100upx;
									color: #F63810;

									text {
										font-size: 32upx;

									}
								}

								.num {
									display: flex;
									// align-items: center;
									text-align: center;
									font-size: 28upx;

									view {
										display: inline-block;
										width: 40upx;
										height: 40upx;
										background-color: #EBEBEB;
										line-height: 40upx;

										&.disabled {
											background-color: #f2f2f2;
											color: #CCCCCC;
										}
									}

									input {
										width: 97upx;
										height: 40upx;
										line-height: 40upx;
										min-height: 40upx;
										margin: 0 10upx; //2
										background-color: #EBEBEB;
									}
								}
							}
						}
					}
				}
			}
		}

		.bottomPay {
			width: 100%;
			height: 112upx;
			background-color: #fff;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 0 28upx;
			position: fixed;
			bottom: 0;
			z-index: 9999;
			box-sizing: border-box;
			checkbox{
				border-radius: 50%;
			}
			.payBox {
				display: flex;
				justify-content: flex-start;
				align-items: center;

				.payNum {
					font-size: 24upx;
					color: #4d4d4d;

					text {
						font-size: 36upx;
						color: #FF484A;
					}
				}

				.payBtn {
					width: 231upx;
					height: 88upx;
					line-height: 88upx;
					background: linear-gradient(0deg, rgba(232, 39, 27, 1), rgba(252, 63, 12, 1));
					border-radius: 44upx;
					color: #fff;
					font-size: 36upx;
					text-align: center;
					margin-left: 30upx;
				}
			}
		}
	}

	.removeM {
		background-color: #ff3b32;
		height: 100%;
		color: #fff;
		padding: 0 20upx;
		font-size: 34upx;
		width: 100upx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>
